package com.lu.pojo.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author luzhenfang
 * @date 2020 05 27
 * @description 通过反射获取类信息
 */

class Cat{
    public int age;
    private int leg;
    private void test(){
        System.out.println("私有方法");
    }
    public int getAge(){
        return age;
    }

    public Cat() {
    }

    public Cat(int age, int leg) {
        this.age = age;
        this.leg = leg;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getLeg() {
        return leg;
    }

    public void setLeg(int leg) {
        this.leg = leg;
    }

    @Override
    public String toString() {
        return "Cat{" +
                "age=" + age +
                ", leg=" + leg +
                '}';
    }
}

public class TestGetClassInfo {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("com.lu.pojo.reflection.Cat");
        // 类的 全限定类名和 类名
        System.out.println(c1.getName());
        System.out.println(c1.getSimpleName());
        // 获得类的属性 (public)
        for (Field field : c1.getFields()) {
            System.out.println(field);

        }
        // 获得类的属性
        for (Field declaredField : c1.getDeclaredFields()) {
            System.out.println(declaredField);
        }
        // 获得指定属性的值
        System.out.println(c1.getField("age"));
        // 获得类的方法(本类及其父类的所有public方法)
        for (Method method : c1.getMethods()) {

            System.out.println(method);
        }
        // 获得本类的所有方法
        for (Method method : c1.getDeclaredMethods()) {

            System.out.println("DeclaredMethod:"+method);
        }
        // 获得指定构造器(public 方法）
        for (Constructor constructor : c1.getConstructors()) {

            System.out.println("constructor:"+constructor);
        }
        // 获得本类构造器(全部方法）
        for (Constructor declaredConstructor : c1.getDeclaredConstructors()) {

            System.out.println("declaredConstructor:"+declaredConstructor);
        }
        // 获得指定构造器
        System.out.println("指定构造器"+c1.getConstructor(int.class, int.class));

    }
}
